/**
 * Created by nico on 2015/12/27.
 */
var async = require('async');
//商品有关的模型
var log4js = require('log4js');
var logger = log4js.getLogger('normal');
var config = require('../config.js');
var activityM = require('../models/activity.js');
var wxjsapi = require('wx_jsapi_sign'); //微信分享必要

module.exports = {
    //摇奖页面
    oldInit:function(req, res, next){
        res.render('activity/luckdraw_new',{title:'幸运大转盘'});
    },
    init : function(req, res, next){
        //首先判断当前路由有没有shareid
        var openid = req.AV.user.get('openid') ;
        var nickname = req.AV.user.get('nickname') ;
        var img = req.AV.user.get('headimgurl') ;
        if(req.query.shareid){
            //分享后的链接,需要获取该shareid已中奖人信息
            activityM.queryShare(req.query.shareid).then(function(data){
                //微信分享
                var url = req.url;
                var wxconfig={
                    appId: config.wx.app_id,
                    appSecret: config.wx.app_secret,
                    cache_json_file:config.wx.cache_json_file
                };
                wxjsapi.getSignature(wxconfig)('http://'+config.domain+url, function(error, result) {
                    if (error) {
                        res.json({
                            'error': error
                        });
                    } else {
                        var welcomeurl='http://'+config.domain+"/share?shareid="+req.query.shareid;
                        res.render('activity/luckdraw',{ title:'幸运大转盘',shareid:req.query.shareid,shareList:data.shareList,share:data.share,rewards:data.rewards,welcomeurl:welcomeurl,appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});

                    }
                });
                // res.render('activity/luckdraw',{title:'幸运大转盘',shareid:req.query.shareid,shareList:data.shareList,share:data.share});
            }).catch(function(err){
                //res.render('activity/luckdraw',{title:'幸运大转盘',shareid:req.query.shareId,shareList:[],share:''});
                //res.render('activity/error',{title:'提示'});
                res.json(err);
            });

        }else{
            //原始链接
            activityM.createNewShare(openid,nickname,img).then(function(data){
                if(data.code === 0 ){
                    //创建成功
                    //微信分享
                    var url = req.url;
                    var wxconfig={
                        appId: config.wx.app_id,
                        appSecret: config.wx.app_secret,
                        cache_json_file:config.wx.cache_json_file
                    };
                    wxjsapi.getSignature(wxconfig)('http://'+config.domain+url, function(error, result) {
                        if (error) {
                            res.json({
                                'error': error
                            });
                        } else {
                            var welcomeurl='http://'+config.domain+"/share?shareid="+data.data.id;
                            res.render('activity/luckdraw',{ title:'幸运大转盘',shareid:data.data.id,share:data.data,shareList :data.shareList,rewards:data.rewards,welcomeurl:welcomeurl,appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});

                        }
                    });

                    //res.render('activity/luckdraw',{title:'幸运大转盘',shareid:data.data.id,share:data.data,shareList :[]});
                }else{
                    //进入手动创建分享页面
                    // console.log('进入手动创建订单');
                    // console.log(data.data);
                    //微信分享
                    var url = req.url;
                    var wxconfig={
                        appId: config.wx.app_id,
                        appSecret: config.wx.app_secret,
                        cache_json_file:config.wx.cache_json_file
                    };
                    wxjsapi.getSignature(wxconfig)('http://'+config.domain+url, function(error, result) {
                        if (error) {
                            res.json({
                                'error': error
                            });
                        } else {
                            var welcomeurl='http://'+config.domain+"/share?shareid="+data.data.share.id;
                            res.render('activity/luckdraw',{ title:'幸运大转盘',shareid:data.data.share.id,share:data.data.share,shareList:data.data.shareList,rewards:data.rewards,welcomeurl:welcomeurl,appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                        }
                    });

                    //res.render('activity/luckdraw',{title:'幸运大转盘',shareid:data.data.share.id,share:data.data.share,shareList:data.data.shareList});
                }
            }).catch(function(err){
                //res.render('activity/error',{title:'提示'});
                res.json(err);

            });
        }
        //res.render('activity/luckdraw',{title:'幸运大转盘'});
    },
    share:function(req, res, next){
        //跳转到分享页面，创建一条新记录
        var openid = req.AV.user.get('openid') ;
        var nickname = req.AV.user.get('nickname') ;
        var img = req.AV.user.get('headimgurl') ;
        var shareid = req.query.shareid ;
        activityM.createNewShare(openid,nickname,img).then(function(data){
            if(data.code === 0 ){
                //创建成功
                //微信分享
                var url = req.url;
                var wxconfig={
                    appId: config.wx.app_id,
                    appSecret: config.wx.app_secret,
                    cache_json_file:config.wx.cache_json_file
                };
                wxjsapi.getSignature(wxconfig)('http://'+config.domain+url, function(error, result) {
                    if (error) {
                        res.json({
                            'error': error
                        });
                    } else {
                        console.log(result.signature);
                        var welcomeurl='http://'+config.domain+"/share?shareid="+data.data.id;
                        //res.send("data.code:"+data.code);
                        res.render('activity/share',{title:'幸运大转盘',shareid:data.data.id,share:data.data,welcomeurl:welcomeurl,appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                        //res.render('myron/share',{appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                        //res.json(result);
                    }
                });
            }else{
                //进入手动创建分享页面(默认页面)
                //微信分享
                var url = req.url;
                var wxconfig={
                    appId: config.wx.app_id,
                    appSecret: config.wx.app_secret,
                    cache_json_file:config.wx.cache_json_file
                };
                wxjsapi.getSignature(wxconfig)('http://'+config.domain+url, function(error, result) {
                    if (error) {
                        res.json({
                            'error': error
                        });
                    } else {
                        console.log(result.signature);
                        var welcomeurl='http://'+config.domain+"/share?shareid="+data.data.share.id;
                        res.render('activity/share',{title:'幸运大转盘',shareid:data.data.share.id,share:data.data.share,shareList:data.data.shareList,welcomeurl:welcomeurl,appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                        //res.render('myron/share',{appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                        //res.json(result);
                    }
                });
                //res.send("data.code:"+data.code);
                //res.render('activity/share',{title:'幸运大转盘',shareid:data.data.id,share:data.data.share,shareList:data.data.shareList});
            }
        }).catch(function(err){
            console.log(err);
            res.json(err);
        });
    },
    //宣传页
    startShare:function(req, res, next){
        var openid = req.AV.user.get('openid') ;
        var nickname = req.AV.user.get('nickname') ;
        var img = req.AV.user.get('headimgurl') ;
        var shareid = req.query.shareid ;

        //微信分享
        var url = req.url;
        var wxconfig={
            appId: config.wx.app_id,
            appSecret: config.wx.app_secret,
            cache_json_file:config.wx.cache_json_file
        };
        wxjsapi.getSignature(wxconfig)('http://'+config.domain+url, function(error, result) {
            if (error) {
                res.json({
                    'error': error
                });
            } else {
                console.log(result.signature);
                var welcomeurl='http://'+config.domain+"/share?shareid="+shareid;
                activityM.countRewardNew().then(function(data){
                    if(data){
                        res.render('activity/start',{ title:'宣传页',shareid:shareid,shareName:nickname,image:img,welcomeurl:welcomeurl,rewards:data, appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                    }
                });
                //res.render('myron/share',{appId:result.appId,timestamp:result.timestamp,nonceStr:result.nonceStr,signature:result.signature});
                //res.json(result);
            }
        });

    },
    startTurntableActivity:function(req, res){
        var uid = req.AV.user.id;
        var openid = req.AV.user.get('openid') ;
        var nickname = req.AV.user.get('nickname') ;
        var img = req.AV.user.get('headimgurl') ;
        //var level = req.params.Level;
        //var activityName = req.params.ActivityName;
        //var level = req.query.Level;
        var activityName = req.query.ActivityName;
        var shareid = req.query.shareid || "";
        var array=  ["哎呀，  就差一点点了！", "满60 减6元", "满30 减2元", "满100 减5元", "现金券 3元","10 积分",'现金券 5角'];

        var newArray = [
            0,1,2,3,4,5,6,0,0,0,
            0,1,2,3,4,5,6,0,0,0,
            0,1,2,3,0,5,6,0,0,0,
            0,1,2,3,4,5,6,0,0,0,
            0,1,2,3,0,5,6,0,0,0,
            0,1,2,3,4,5,6,0,0,0,
            0,1,2,3,0,5,6,0,0,0,
            0,1,2,3,0,5,6,0,0,0,
            0,1,2,3,0,5,0,0,0,0,
            0,1,2,3,0,5,0,0,0,0
        ] ;
        //var random = Math.floor(Math.random()*(newArray.length)+1);
        var random = parseInt((Math.random()*100))%(newArray.length) ;
        //var random = 2;
        var item = newArray[random];
        if(item === 1 || item===4 || item===7){
            item = 0 ;
        }
        var angles = (item+1) * (360 / array.length) - (360 / (array.length*2));
        if(angles<270){
            angles = 270 - angles;
        }else{
            angles = 360 - angles + 270;
        }
        var level = "L"+(item) ;
        var remark = array[item];
        async.waterfall([
            function(callback){
                if(shareid){
                    activityM.isTurntabledInShare(openid,shareid).then(function(data){
                        if(data.code === 0){
                            callback(null, {code:0})
                        }else{
                            callback({data:data,angles:angles});
                        }
                    }).catch(function(err){
                        callback({data:err,angles:angles});
                    });
                }else{
                    callback(null, {code:0});
                }

            },
            function(data,callback){
                if(data.code === 0){
                    activityM.turntableActivity(uid,level,activityName,openid,nickname,img,shareid,remark).then(function(data){
                        callback(null, {data:data,angles:angles});
                    }).catch(function(err){
                        //出错或者不能抽奖
                        callback({data:err,angles:angles});
                    });
                }else{
                    callback({data:{code:-1,msg:'出错了',angles:angles}});
                }
            }
        ],function(err,result){
            if(err){
                res.json(err);
            }else{
                res.json(result);
            }
        })

    },

    gameOver:function(req, res, next){
        res.render('activity/gameOver',{title:'活动结束'});
    }
}
